let utils = {}
// md5加密
utils.md5 = (str) => {
  let crypto = require('crypto')
  let md5 = crypto.createHash('md5')
  md5.update(str)
  return md5.digest('hex')
}

// 获取token
utils.getToken = () => localStorage.getItem('token')

// 计算sign
utils.getSign = (params) => {
  let sorted = Object.keys(params).sort()
  let basestring = process.env.VUE_APP_APP_SECRET
  const type = ['undefined', 'object', 'function']
  for (let i = 0, l = sorted.length; i < l; i++) {
    if (sorted[i] === 'sign') {
      continue
    }
    let k = sorted[i]
    if (type.indexOf(typeof params[k]) === -1) {
      basestring += k + (typeof params[k] === 'boolean' ? Number(params[k]) : params[k])
    }
  }
  basestring += process.env.VUE_APP_APP_SECRET
  return utils.md5(basestring)
}

// 添加默认参数及签名
utils.setDefaultParams = (config) => {
  config.data['token'] = this.getToken()
  config.data['appkey'] = process.env.VUE_APP_APP_KEY
  config.data['timestamp'] = Math.round(new Date() / 1000) + 100
  config.data['format'] = 'json'
  config.data['sign'] = utils.getSign(Object.assign(config.data, config.params))
}

export default utils
